//
//  SJTreeViewController.m
//  WSL
//
//  Created by CJ on 2017/11/21.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJTreeViewController.h"
#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJTreeApi.h"
#import "SJMovePosApi.h"
#import "SJPublishApi.h"
#import "SJSpaceStationAddApi.h"
#import "SJSpaceStationDelApi.h"
#import "SJSpaceStationCancelApi.h"
#import "SJUnFollowPersonApi.h"
#import "SJFollowPersonApi.h"
#import "SJSSAddApi.h"
#import "SJDelBlockApi.h"

#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

#import <JPVideoPlayer/UIView+WebVideoCache.h>
#import <AVFoundation/AVFoundation.h>

#import "SJUploadBar.h"
#import "SJFunctionBar.h"
#import "SJOtherFunctionBar.h"
#import "SJUserInfoItem.h"
#import "SJTreeHeaderView.h"

#import "SJAddWordViewController.h"
#import "SJAddPicViewController.h"
#import "SJAddFromSSViewController.h"
#import "SJAddTxtViewController.h"
#import "SJTxtDetailViewController.h"

#import "SJPersonalViewController.h"
#import "SJEditTxtViewController.h"
#import "SJEditPicViewController.h"
#import "SJEditAudioViewController.h"
#import "SJEditVideoViewController.h"
#import "SJEditWordViewController.h"

#import "SJShareBar.h"
#import "SJBlockItem.h"
#import "SJSearchViewController.h"
#import "SJReportView.h"
#import "SJReportApi.h"


#import "SJLabelViewController.h"
#import "SJLabelItem.h"

@interface SJTreeViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate, JTSImageViewControllerAnimationDelegate, JPVideoPlayerDelegate, SJUploadBarDelegate, SJShareBarDelegate, SJSJReportViewDelegate>

////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) SJCustomLayout *customLayout;

@property (nonatomic, copy) NSString *t;
@property (nonatomic, copy) NSString *l;
@property (nonatomic, copy) NSString *w;
@property (nonatomic, copy) NSString *h;


@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;
@property (nonatomic, copy) NSString *isMove;
@property (nonatomic, strong) UIView *snapshot;
@property (nonatomic, strong) SJOneCell *selectedCell;
@property (nonatomic, assign) CGPoint touchPoint;
@property (nonatomic, copy) NSString *autoScrollDirection; // 1:上 2:下
@property (nonatomic, strong) CADisplayLink *autoScrollTimer;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;

// 视频
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) SJWordItem *selectedItem;
@property (nonatomic, strong) UIView *videoContainer;

@property (nonatomic, strong) UIView *detailImageView;
@property (strong, nonatomic) UILabel *detailLabel;


/////////  navigationBar
@property (nonatomic, strong) SJUserInfoItem *userItem; // 0级词的 owner
@property (nonatomic, strong) UIView *navigationBarView; // 背景
@property (strong, nonatomic) UIImageView *avatarImageView;


@property (strong, nonatomic) UIButton *displayButton;
@property (nonatomic, copy) NSString *isDisplayTitle;

@property (strong, nonatomic) UIButton *followButton;
@property (nonatomic, copy) NSString *isFollow;


@property (nonatomic, strong) NSMutableArray *items;
@property (strong, nonatomic) UIButton *preButton;
@property (strong, nonatomic) UIButton *nextButton;


@property (strong, nonatomic) NSMutableArray *optionArray;
@property (strong, nonatomic) JTSImageViewController *imageViewer;


@property (nonatomic, strong) UIView *touchView;

// 功能版
@property (nonatomic, strong) UIView *funcView;
@property (nonatomic, strong) SJBlockItem *blockItem; //


@property (strong, nonatomic) UIButton *selectedRptButton;


@property (strong, nonatomic) NSDate *startDate;

@end

@implementation SJTreeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat y = scrollView.contentOffset.y;
    CGFloat top = scrollView.contentInset.top;
    
    WeakSelf;
    if (y - 10 <= -top || y == -SJLayoutFrame(50)) {
        
        [UIView animateWithDuration:.2 animations:^{
            
            weakSelf.avatarImageView.alpha = 1;
        }];
        
    } else {
        
        [UIView animateWithDuration:.2 animations:^{
            
            weakSelf.avatarImageView.alpha = 0;
        }];
    }
}

- (void)dealloc {
    SJLogFunc;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:@"item" context:nil];
    [self stopAutoScrollTimer];
    
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:self.startDate] * 1000;
    int millisecond = interval;
    self.startDate = [NSDate date];
    
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[@"ID"] = self.item.ID;
    attributes[@"content"] = self.item.content;
    attributes[@"fmt"] = self.item.fmt;
    [SJStatisticTool event:@"tree_zeroWordTime" attributes:attributes durations:millisecond];
   
}

- (void)didAddOneWordNotification:(NSNotification *)notification {
    
    SJWordItem *item = notification.userInfo[@"item"];
    [self.dataArray addObject:item];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0];
    [self.collectionView insertItemsAtIndexPaths:@[indexPath]];
}

- (void)didEditWordNotification:(NSNotification *)notification {
    
    SJWordItem *item = notification.userInfo[@"item"];
    
    for (SJWordItem *wItem in self.dataArray) {
        if ([item.ID isEqualToString:wItem.ID]) {
            [self.dataArray removeObject:wItem];
            [self.dataArray addObject:item];
            [self.collectionView reloadData];
            break;
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didAddOneWordNotification:) name:SJDidAddOneWordNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEditWordNotification:) name:SJDidEditWordNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeNode) name:UIApplicationWillResignActiveNotification object:nil];
    
    self.isDisplayTitle = @"0";
    self.page = 0;
    [self.items addObject:self.item];
    [self setupUI];
    [self loadNewData];
    
    // 用于统计事件
    self.startDate = [NSDate date];
    [self addObserver:self forKeyPath:@"item" options:NSKeyValueObservingOptionOld context:nil];
}

/** 添加观察者必须要实现的方法 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    SJWordItem *old = [change objectForKey:@"old"];
    
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:self.startDate] * 1000;
    int millisecond = interval;
    self.startDate = [NSDate date];
    
    if ([keyPath isEqualToString:@"item"]) {
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"ID"] = old.ID;
        attributes[@"content"] = old.content;
        attributes[@"fmt"] = old.fmt;
        [SJStatisticTool event:@"tree_zeroWordTime" attributes:attributes durations:millisecond];
    }
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
    [self.view addSubview:self.preButton];
    self.preButton.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(11))
    .bottomSpaceToView(self.view, SJLayoutFrame(21))
    .heightIs(SJLayoutFrame(40))
    .widthIs(SJLayoutFrame(40));
    
    
    [self.view addSubview:self.nextButton];
    self.nextButton.sd_layout
    .rightSpaceToView(self.view, SJLayoutFrame(11))
    .bottomSpaceToView(self.view, SJLayoutFrame(21))
    .heightIs(SJLayoutFrame(40))
    .widthIs(SJLayoutFrame(40));
    
    
    [self.view addSubview:self.avatarImageView];
    self.avatarImageView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(11))
    .centerYEqualToView(self.navigationBarView)
    .heightIs(SJLayoutFrame(40))
    .widthIs(SJLayoutFrame(40));
    
}

#pragma mark - getter

- (UIView *)touchView {
    
    if (!_touchView) {
        
        _touchView = [UIView new];
        
        UIImageView *touchImageView = [UIImageView new];
        touchImageView.image = [UIImage imageNamed:@"sicang_icon_position"];
        
        [_touchView addSubview:touchImageView];
        touchImageView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
        
    }
    return _touchView;
}

- (NSMutableArray *)items {
    
    if (!_items) {
        
        _items = [[NSMutableArray alloc] init];
        
    }
    return _items;
}


- (UIButton *)preButton {
    
    if (!_preButton) {
        
        _preButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_preButton setImage:[UIImage imageNamed:@"01_icon_slide_left"] forState:UIControlStateNormal];
        [_preButton addTarget:self action:@selector(preAction) forControlEvents:UIControlEventTouchUpInside];
        _preButton.hidden = YES;
        
    }
    return _preButton;
}

- (void)preAction {
    
    NSInteger index = [self.items indexOfObject:self.item];
    if (index > 0) {
        
        if (index == 1) {
            self.preButton.hidden = YES;
        }
        
        self.item.offsetY = [NSString stringWithFormat:@"%f", self.collectionView.contentOffset.y];
        
        self.nextButton.hidden = NO;
        self.item = [self.items objectAtIndex:index - 1];
        
        self.dataArray = [self.item.subWords mutableCopy];
        
        self.userItem = [SJUserInfoItem modelWithJSON:[self.item.userItem mutableCopy]];
        self.blockItem = [SJBlockItem modelWithJSON:[self.item.blockItem mutableCopy]];
        
        [self.avatarImageView setImageWithURL:[NSURL URLWithString:self.userItem.avatar] placeholder:[UIImage imageNamed:@"common_icon_defaultavatar"]];
        
        [self.collectionView reloadData];
        [self.collectionView setContentOffset:CGPointMake(0, [self.item.offsetY floatValue]) animated:NO];
        
    }
}

- (void)nextAction {
    
    NSInteger index = [self.items indexOfObject:self.item];
    if (index + 1 < self.items.count) {
        
        if (index + 2 == self.items.count) {
            self.nextButton.hidden = YES;
        }
        
        self.item.offsetY = [NSString stringWithFormat:@"%f", self.collectionView.contentOffset.y];
        
        self.preButton.hidden = NO;
        self.item = [self.items objectAtIndex:index + 1];
        
        self.dataArray = [self.item.subWords mutableCopy];
        
        self.userItem = [SJUserInfoItem modelWithJSON:[self.item.userItem mutableCopy]];
        self.blockItem = [SJBlockItem modelWithJSON:[self.item.blockItem mutableCopy]];
        
        [self.avatarImageView setImageWithURL:[NSURL URLWithString:self.userItem.avatar] placeholder:[UIImage imageNamed:@"common_icon_defaultavatar"]];
        
        [self.collectionView reloadData];
        [self.collectionView setContentOffset:CGPointMake(0, [self.item.offsetY floatValue]) animated:NO];
    }
}

- (UIButton *)nextButton {
    
    if (!_nextButton) {
        
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setImage:[UIImage imageNamed:@"01_icon_slide_right"] forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
        _nextButton.hidden = YES;
        
    }
    return _nextButton;
}

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"01_icon_return_Suspension"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(_navigationBarView, SJLayoutFrame(11))
        .heightIs(SJLayoutFrame(40))
        .widthIs(SJLayoutFrame(40));
        
        // 更多
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setImage:[UIImage imageNamed:@"01_icon_more_Suspension"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:moreButton];
        moreButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(backButton, SJLayoutFrame(5))
        .heightIs(SJLayoutFrame(40))
        .widthIs(SJLayoutFrame(40));
    
    }
    return _navigationBarView;
}


- (void)shareBar:(SJShareBar *)uploadBar didSelectItemAtIndex:(NSInteger)index button:(UIButton *)button {
    
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 头像
            [weakSelf avatarAction];
        }
        
        if (index == 1) {
            
            if ([weakSelf isMe]) { // 发布
                [weakSelf publishAction];
                
            } else { // 收藏
                [weakSelf subscribeAction];
            }
        }
        
        if (index == 2) { // 搜索
            [weakSelf searchAction];
        }
        
        if (index == 3) { // 举报
            [weakSelf reportAction];
            
        }
        
        if (index == 4) { // 微信
            
            [weakSelf shareWithPlatform:SSDKPlatformSubTypeWechatSession];
            
        }
        
        if (index == 5) { // 朋友圈
            
            [weakSelf shareWithPlatform:SSDKPlatformSubTypeWechatTimeline];
        }
        
        if (index == 6) { // QQ
            
            [weakSelf shareWithPlatform:SSDKPlatformSubTypeQQFriend];
        }
        
        if (index == 7) { // 微博
            
            [weakSelf shareWithPlatform:SSDKPlatformTypeSinaWeibo];
        }
        
        if (index == 8) { // 眼睛
            
            [weakSelf displayWithButton:button];
            
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            attributes[@"name"] = @"显示标题";
            [SJStatisticTool event:@"tree_DisplayTitle" attributes:attributes];
        }
        
    }];
}


/**
 举报
 */
- (void)reportAction {
    
    SJReportView *reportView = [[SJReportView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    reportView.delegate = self;
    
    WeakSelf;
    [LEEAlert alert].config
    .LeeAddCustomView(^(LEECustomView *custom) {
        custom.view = reportView;
        custom.isAutoWidth = YES;
    })
    .LeeCornerRadius(0)
    .LeeHeaderColor([UIColor clearColor])
    .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
    .LeeHeaderInsets(UIEdgeInsetsZero)
    .LeeClickBackgroundClose(YES)
    .LeeCloseComplete(^{
        [weakSelf.view endEditing:YES];
        self.selectedRptButton = nil;
    })

    .LeeShow();
}


- (void)reportView:(SJReportView *)reportView didSelectItemAtIndex:(NSInteger)index button:(UIButton *)button {
    
    if (index == 0) {  // 提交
        
        if (!self.selectedRptButton) {
                        
            return;
        }
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"item"] = [NSString stringWithFormat:@"%ld", (long)self.selectedRptButton.tag];
        parameters[@"content"] = reportView.reportTextView.text?reportView.reportTextView.text:@"";
        parameters[@"report_id"] = self.item.ID;
        
        SJReportApi *api = [[SJReportApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                
                [LEEAlert closeWithCompletionBlock:^{
                    
                    [SVProgressHUD showInfoWithStatus:@"已举报"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });
                    
                }];
                
                
                NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
                attributes[@"name"] = @"举报";
                attributes[@"ID"] = self.item.ID;
                attributes[@"content"] = self.item.content;
                attributes[@"fmt"] = self.item.fmt;
                [SJStatisticTool event:@"tree_report" attributes:attributes];
             
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
        
        return;
    }
    
    self.selectedRptButton.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
    button.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
    self.selectedRptButton = button;
    
}

- (void)displayWithButton:(UIButton *)button {
    
    if ([self.isDisplayTitle isEqualToString:@"1"]) {
        self.isDisplayTitle = @"0";
    } else {
        self.isDisplayTitle = @"1";
    }
    
    [self.collectionView reloadData];
  
}

- (void)shareWithPlatform:(SSDKPlatformType)platformType {
    
    NSString *urlStr = [NSString stringWithFormat:@"http://dfka.sanjuetech.com/ai_h5/index?pid=%@&id=%@&uid=%@", self.item.bid, self.item.ID, self.blockItem.user_info.ID];
    
    NSString *imgStr = self.blockItem.user_info.avatar;
    
    if (imgStr.length == 0 || !imgStr) {
        
        imgStr = [[NSBundle mainBundle] pathForResource:@"Icon-60" ofType:@"png"];
    }
    
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[@"name"] = @"分享";
    attributes[@"platformType"] = [NSString stringWithFormat:@"%lu", (unsigned long)platformType];
    [SJStatisticTool event:@"tree_Share" attributes:attributes];
    
    [self share:platformType imageArray:@[imgStr] content:@"我在思藏找到了张国荣的舅舅的二姨留下的收藏 ，速来围观" title:@"青春不打烊  思藏不打码" url:urlStr];
}

- (void)shareAction {
    
    SJShareBar *shareBar = [[SJShareBar alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    shareBar.item = self.blockItem;
    
    if ([self.isDisplayTitle isEqualToString:@"1"]) {
        shareBar.isDisplay = YES;
    } else {
        shareBar.isDisplay = NO;
    }
    
    shareBar.delegate = self;
    
    [LEEAlert actionsheet].config
    .LeeAddCustomView(^(LEECustomView *custom) {
        custom.view = shareBar;
    })
    .LeeHeaderColor([UIColor clearColor])
    .LeeBackGroundColor(SJColorHexString(@"#000000"))
    .LeeActionSheetBottomMargin(SJLayoutFrame(11))
    .LeeBackgroundStyleTranslucent(0.7f)
    .LeeHeaderInsets(UIEdgeInsetsZero)
    .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
        return SJScreenW;
    })
    .LeeShow();

}

- (void)searchAction {
    
    SJSearchViewController *searchVC = [SJSearchViewController new];
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)avatarAction {
    
    SJPersonalViewController *personVC = [SJPersonalViewController new];
    
    SJUserInfoItem *userInfo = [SJUserInfoItem modelWithJSON:[SJUserDefaults objectForKey:SJUserInfo]];
    if ([userInfo.ID isEqualToString:self.userItem.ID]) {
        personVC.isMe = YES;
    } else {
        personVC.isMe = NO;
    }
    personVC.fid = self.userItem.ID;
    
    [self.navigationController pushViewController:personVC animated:YES];
}

- (UIImageView *)avatarImageView {
    
    if (!_avatarImageView) {
        _avatarImageView = [UIImageView new];
        _avatarImageView.sd_cornerRadiusFromHeightRatio = @(0.5);
        _avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
        _avatarImageView.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        _avatarImageView.layer.borderWidth = SJLayoutFrame(1);//边框宽度
        
        _avatarImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarAction)];
        [_avatarImageView addGestureRecognizer:singleTap];
    }
    return _avatarImageView;
}

- (void)subscribeAction {
    
    if ([self.blockItem.is_subscribe isEqualToString:@"2"]) { // 已订阅，取消
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"bid"] = self.item.bid;
        parameters[@"fid"] = self.userItem.ID;
        
        SJSpaceStationCancelApi *api = [[SJSpaceStationCancelApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                
                self.blockItem.is_subscribe = @"1";
                
                self.item.is_subscribe = self.blockItem.is_subscribe;
                [self.collectionView reloadData];
                
                [SVProgressHUD showInfoWithStatus:@"取消收藏"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                
                
                NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
                attributes[@"name"] = @"取消收藏";
                attributes[@"ID"] = self.item.ID;
                attributes[@"content"] = self.item.content;
                attributes[@"fmt"] = self.item.fmt;
                [SJStatisticTool event:@"tree_unsubscribe" attributes:attributes];
                
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
        
    } else {
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"bid"] = self.item.bid;
        parameters[@"w"] = self.item.w;
        parameters[@"h"] = self.item.h;
        parameters[@"fid"] = self.userItem.ID;
        parameters[@"source"] = @"5";
        
        SJSSAddApi *api = [[SJSSAddApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                
                self.blockItem.is_subscribe = @"2";
                
                self.item.is_subscribe = self.blockItem.is_subscribe;
                [self.collectionView reloadData];
                
                [SVProgressHUD showInfoWithStatus:@"收藏成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                
                NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
                attributes[@"name"] = @"收藏";
                attributes[@"ID"] = self.item.ID;
                attributes[@"content"] = self.item.content;
                attributes[@"fmt"] = self.item.fmt;
                [SJStatisticTool event:@"tree_subscribe" attributes:attributes];
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
    }
}

- (void)publishWithStatus:(NSString *)status classify:(NSArray *)classify {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"bid"] = self.item.bid;
    parameters[@"id"] = self.item.ID;
    parameters[@"w"] = self.item.w;
    parameters[@"h"] = self.item.h;
    parameters[@"status"] = status;  // 1 取消发布 2 发布
    
    if (classify != nil) {
        
        NSMutableArray *array = [NSMutableArray array];
        
        for (SJLabelItem *item in classify) {
            [array addObject:item.ID];
        }
        
        NSString *classifyJson = [array jsonStringEncoded];
        
        parameters[@"classify"] = classifyJson;
    }
    
    SJPublishApi *api = [[SJPublishApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.blockItem.is_published = api.responseObject[@"content"][@"is_published"];
            self.item.is_published = self.blockItem.is_published;
            [self.collectionView reloadData];
            
            NSString *msg = @"";
            if ([self.blockItem.is_published isEqualToString:@"2"]) { // 已发布
                msg = @"发布成功";
            } else {
                msg = @"取消发布";
            }
            
            [SVProgressHUD showInfoWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            attributes[@"name"] = @"发布";
            attributes[@"ID"] = self.item.ID;
            attributes[@"content"] = self.item.content;
            attributes[@"fmt"] = self.item.fmt;
            [SJStatisticTool event:@"tree_publish" attributes:attributes];
            
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showInfoWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
    
}


- (void)publishAction {
    
    
    if ([self.blockItem.is_published isEqualToString:@"2"]) { // 当前已发布，取消发布
        
        [self publishWithStatus:@"1" classify:nil];
    } else {
        
        SJLabelViewController *labelVC = [SJLabelViewController new];
        [self addChildViewController:labelVC];
        [self.view addSubview:labelVC.view];
        labelVC.view.frame = CGRectMake(0, 0, SJScreenW, SJScreenH);
        WeakSelf;
        labelVC.doneBlock = ^(NSArray *array) {
            
            [weakSelf publishWithStatus:@"2" classify:array];
        };
    }

}

- (void)saveImage:(UIImage *)image {
    //save to photosAlbum
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *barItemTitle = @"保存成功";
    if (error != nil) {
        barItemTitle = @"保存失败";
    }
    
    SJLog(@"%@", barItemTitle);
    
}

- (UIView *)detailImageView{
    
    if (!_detailImageView) {
        
        _detailImageView = [UIView new];
        _detailImageView.backgroundColor = SJColorHexString(@"#00000090");
//        _detailImageView.alpha = 0;
        
        
        UIButton * moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setImage:[UIImage imageNamed:@"detail_btn_more_nor"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
        
        
        [_detailImageView addSubview:self.detailLabel];
        self.detailLabel.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(9), SJLayoutFrame(13), SJLayoutFrame(9), SJLayoutFrame(50)));
        
    }
    return _detailImageView;
}


- (void)editFilter {
    
    // 检索
    int max_t = 0;
    for (SJWordItem *item in self.dataArray) {
        
        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }
    
    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    for (int i = 0; i < max_t + max_w; i++) {
        
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];
        
        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }
    
    for (SJWordItem *item in self.dataArray) {
        
        if (item == self.selectedItem) {
            continue;
        }
        
        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        for (int i = t; i < t + h; i++) {
            
            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }
    
    int l2r = 0;
    NSMutableArray *optArray = [NSMutableArray array];
    
    if ([self.selectedItem.t intValue] >= arrlt.count - max_w) {
        
        int maxOptW = max_w - [self.selectedItem.l intValue];
        int maxOptH = max_w;
        
        for (int i = 0; i < maxOptH; i++) {
            
            for (int j = 0; j < maxOptW; j++) {
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = [NSString stringWithFormat:@"%d", i + 1];
                dict[@"w"] = [NSString stringWithFormat:@"%d", j + 1];
                [optArray addObject:dict];
            }
        }
        
    } else {
        
        for (int i = [self.selectedItem.l intValue]; i < max_w; i++) { // 第1行
            
            if ([arrlt[[self.selectedItem.t intValue]][i] isEqualToNumber: @0]) {
                
                l2r = i - [self.selectedItem.l intValue] + 1;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = @"1";
                dict[@"w"] = [NSString stringWithFormat:@"%d", l2r];
                [optArray addObject:dict];
                
            } else {
                break;
            }
        }
        
        for (int n = 1; n < max_w; n++) { // 2 ~ max_w 行
            
            for (int i = [self.selectedItem.l intValue]; i < max_w; i++) {
                
                if ([arrlt[[self.selectedItem.t intValue] + n][i] isEqualToNumber: @0]) {
                    
                    if (i - [self.selectedItem.l intValue] + 1 <= l2r) {
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        dict[@"h"] = [NSString stringWithFormat:@"%d", n + 1];
                        dict[@"w"] = [NSString stringWithFormat:@"%d", i - [self.selectedItem.l intValue] + 1];
                        [optArray addObject:dict];
                    } else {
                        break;
                    }
                    
                } else {
                    l2r = i - [self.selectedItem.l intValue];
                    break;
                }
            }
        }
    }
    
    if (optArray.count == 0) {
        return;
    }
    
    self.optionArray = optArray;
    
}

- (void)moreAction {
    
    if ([self.selectedItem.is_me isEqualToString:@"1"]) { // 自己
        
//        SJFunctionBar *functionBar = [[SJFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
//        functionBar.delegate = self;
//
//        [LEEAlert actionsheet].config
//        .LeeAddCustomView(^(LEECustomView *custom) {
//            custom.view = functionBar;
//        })
//        .LeeCornerRadius(SJCornerRadius)
//        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
//        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
//        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
//            return SJScreenW - SJLayoutFrame(14);
//        })
//        .LeeHeaderInsets(UIEdgeInsetsZero)
//        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
//        .LeeShow();
        
    } else {
        
//        SJOtherFunctionBar *functionBar = [[SJOtherFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
//        functionBar.delegate = self;
//
//        [LEEAlert actionsheet].config
//        .LeeAddCustomView(^(LEECustomView *custom) {
//            custom.view = functionBar;
//        })
//        .LeeCornerRadius(SJCornerRadius)
//        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
//        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
//        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
//            return SJScreenW - SJLayoutFrame(14);
//        })
//        .LeeHeaderInsets(UIEdgeInsetsZero)
//        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
//        .LeeShow();
    }
    
}

- (UILabel *)detailLabel {
    
    if (!_detailLabel) {
        
        _detailLabel = [UILabel new];
        _detailLabel.textColor = SJColorHexString(@"#ffffffff");
        _detailLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        
    }
    return _detailLabel;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (UILongPressGestureRecognizer *)longPressGesture {
    
    if (!_longPressGesture) {
        
        _longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
        _longPressGesture.minimumPressDuration = .3;
        
    }
    return _longPressGesture;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(50), 0, 0, 0);
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
        [_collectionView registerClass:[SJTreeHeaderView class] forSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SJTreeHeaderView class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        [_collectionView addGestureRecognizer:self.longPressGesture];
        
    }
    
    return _collectionView;
}

- (void)showTrash {
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    [self.view addSubview:self.funcView];
    
    if (812 == SJScreenH) {
        self.funcView.sd_layout
        .bottomSpaceToView(self.view, SJLayoutFrame(11) + 18)
        .leftSpaceToView(self.view, SJLayoutFrame(17))
        .widthIs(SJScreenW - SJLayoutFrame(34))
        .heightIs(SJLayoutFrame(60));
    } else {
        self.funcView.sd_layout
        .bottomSpaceToView(self.view, SJLayoutFrame(11))
        .leftSpaceToView(self.view, SJLayoutFrame(17))
        .widthIs(SJScreenW - SJLayoutFrame(34))
        .heightIs(SJLayoutFrame(60));
    }
    
    [UIView animateWithDuration:.25 animations:^{
        self.funcView.alpha = 1;
    }];
}

- (void)hideTrash {
    
    [UIView animateWithDuration:.25 animations:^{
        self.funcView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.funcView removeFromSuperview];
        self.funcView = nil;
    }];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)gesture {
    
    switch (gesture.state) { // 移动
            
        case UIGestureRecognizerStateBegan: {
            
            CGPoint touchPoint = [gesture locationInView:self.collectionView];
            NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:touchPoint];
            self.touchPoint = touchPoint;
            
            CGFloat headerH = [self collectionView:nil layout:nil heightForHeaderInSection:0];
            if (touchPoint.y < headerH) {
                return;
            }
            
            if (touchIndexPath) {
                
                [self cellSelectedAtIndexPath:touchIndexPath];
                
                // 显示废纸篓
                [self showTrash];
                
            } else {
                
                if (![self isMe]) {
                    return;
                }
                
                NSInteger l = (NSInteger)(touchPoint.x / ((SJScreenW - SJMargin) / SJItemCount));
                NSInteger t = (NSInteger)((touchPoint.y - headerH + SJMargin) / ((SJScreenW - SJMargin) / SJItemCount));
                
                self.l = [NSString stringWithFormat:@"%ld", (long)l];
                self.t = [NSString stringWithFormat:@"%ld", (long)t];
                
                // 添加新的
                [self addItem];
                
            }
        }
            break;
        case UIGestureRecognizerStateChanged: {
            
            if (self.snapshot) {
                
                CGPoint touchPoint = [gesture locationInView:self.collectionView];
                [self gestureChangedAtPoint:touchPoint];
                
                touchPoint = [self.collectionView convertPoint:touchPoint toView:self.view];
                
                if (CGRectContainsPoint(self.funcView.frame, touchPoint)) { // 功能版
                    
                    [self funcChangedAction:touchPoint];
                    
                } else {
                    
                    for (UIButton *btn in self.funcView.subviews) {
                        btn.selected = NO;
                    }
                }
            }
        }
            break;
        case UIGestureRecognizerStateEnded: {
            
            if (self.snapshot) {
                
                CGPoint touchPoint = [gesture locationInView:self.collectionView];
                touchPoint = [self.collectionView convertPoint:touchPoint toView:self.view];
                
                [self.collectionView removeGestureRecognizer:self.longPressGesture];
                if (CGRectContainsPoint(self.funcView.frame, touchPoint)) { // 功能版
                    
                    [self funcAction:touchPoint];
                    
                } else { // 移动
                    
                    if (![self isMe]) {
                        
                        [self hideTrash];
                        [self stopAutoScrollTimer];
                        [self removeNode];
                        [SVProgressHUD showInfoWithStatus:@"不可操作"];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                        });
                        return;
                    }
                    
                    [self gestureEnded];
                    [self hideTrash];
                }
            }
        }
            break;
            
        default:
            break;
    }
}

- (BOOL)isMe {
    
    // 判断是不是自己
    SJUserInfoItem *myInfo = [SJUserInfoItem modelWithJSON:[SJUserDefaults objectForKey:SJUserInfo]];
    
    return [myInfo.ID isEqualToString:self.userItem.ID];
}


- (void)funcChangedAction:(CGPoint)point {
    
    CGPoint touchPoint = [self.view convertPoint:point toView:self.funcView];
    
    for (UIButton *btn in self.funcView.subviews) {
        
        btn.selected = NO;
        if (CGRectContainsPoint(btn.frame, touchPoint)) {
            
            btn.selected = YES;
        }
    }
}


- (UIView *)funcView {
    
    if (!_funcView) {
        
        _funcView = [UIView new];
        _funcView.backgroundColor = [UIColor clearColor];
        _funcView.alpha = 0;
        
        UIButton *btn_0 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_0 setImage:[UIImage imageNamed:@"sicang_icon_copy_nor"] forState:UIControlStateNormal];
        [btn_0 setImage:[UIImage imageNamed:@"sicang_icon_copy_sel"] forState:UIControlStateSelected];
        btn_0.tag = 0;
        [_funcView addSubview:btn_0];
        
        UIButton *btn_1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_1 setImage:[UIImage imageNamed:@"sicang_icon_edit_nor"] forState:UIControlStateNormal];
        [btn_1 setImage:[UIImage imageNamed:@"sicang_icon_edit_sel"] forState:UIControlStateSelected];
        btn_1.tag = 1;
        
        if ([self.selectedItem.is_me isEqualToString:@"1"]) {
            
            [_funcView addSubview:btn_1];
            
        }
        
//        if ([self isMe]) {
//            [_funcView addSubview:btn_1];
//        }

        UIButton *btn_2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_2 setImage:[UIImage imageNamed:@"sicang_icon_cut_nor"] forState:UIControlStateNormal];
        [btn_2 setImage:[UIImage imageNamed:@"sicang_icon_cut_sel"] forState:UIControlStateSelected];
        btn_2.tag = 2;
        
        if ([self isMe]) {
            [_funcView addSubview:btn_2];
        }
        
        UIButton *btn_3 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_3 setImage:[UIImage imageNamed:@"sicang_icon_deletet_nor"] forState:UIControlStateNormal];
        [btn_3 setImage:[UIImage imageNamed:@"sicang_icon_deletet_sel"] forState:UIControlStateSelected];
        btn_3.tag = 3;
        
        if ([self isMe]) {
            [_funcView addSubview:btn_3];
        }
        
        btn_0.sd_layout.heightIs(SJLayoutFrame(60));
        btn_1.sd_layout.heightIs(SJLayoutFrame(60));
        btn_2.sd_layout.heightIs(SJLayoutFrame(60));
        btn_3.sd_layout.heightIs(SJLayoutFrame(60));
        
        NSMutableArray *temp = [NSMutableArray new];
        [temp addObject:btn_0];
        [temp addObject:btn_1];
        [temp addObject:btn_2];
        [temp addObject:btn_3];
        
        [_funcView setupAutoMarginFlowItems:[temp copy] withPerRowItemsCount:temp.count itemWidth:SJLayoutFrame(60) verticalMargin:0 verticalEdgeInset:0 horizontalEdgeInset:0];
        
    }
    return _funcView;
}


- (void)funcAction:(CGPoint)point {
    
    CGPoint touchPoint = [self.view convertPoint:point toView:self.funcView];
    
    for (UIButton *btn in self.funcView.subviews) {
        
        if (CGRectContainsPoint(btn.frame, touchPoint)) {
            
            [self functionAction:btn.tag];
            break;
            
        } else {
            
            [self hideTrash];
            [self stopAutoScrollTimer];
            [self removeNode];
            
        }
    }
}

- (void)functionAction:(NSInteger)tag {
    
    if (tag == 0) { // copy
        
        [self cpToFavorite];
    } else if (tag == 1) { // edit
        
        [self editItem];
    } else if (tag == 2) { // cut
        
        [self moveToFavorite];
    } else if (tag == 3) { // delete
        
        [self deleteItem];
    }
}



- (void)deleteItem {
    
    if (![self isMe]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    
    SJDelBlockApi *api = [[SJDelBlockApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            [self.dataArray removeObject:item];
            [self.collectionView deleteItemsAtIndexPaths:@[touchIndexPath]];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self.collectionView addGestureRecognizer:self.longPressGesture];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"删除";
        attributes[@"ID"] = item.ID;
        attributes[@"content"] = item.content;
        attributes[@"fmt"] = item.fmt;
        [SJStatisticTool event:@"deleteItem" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
    }];
}


- (void)editItem {
    
    if (![self isMe]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    [self.imageViewer dismiss:NO];
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    [self editFilter];
    
    if ([item.fmt isEqualToString:@"1"]) { // 词条
        
        SJEditWordViewController *editVC = [SJEditWordViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        SJEditPicViewController *editVC = [SJEditPicViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        SJEditAudioViewController *editVC = [SJEditAudioViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        SJEditVideoViewController *editVC = [SJEditVideoViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"11"]) { //
        
        SJEditTxtViewController *editVC = [SJEditTxtViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    [self hideTrash];
    [self stopAutoScrollTimer];
    [self removeNode];
    
}


- (void)cpToFavorite {
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    if ([item.can_fav isEqualToString:@"1"]) {
        
        [SVProgressHUD showInfoWithStatus:@"内容受作者保护"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    parameters[@"source"] = @"6";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"复制成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"复制";
        attributes[@"ID"] = item.ID;
        attributes[@"content"] = item.content;
        attributes[@"fmt"] = item.fmt;
        [SJStatisticTool event:@"copyItem" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
    }];
}

- (void)moveToFavorite {
    
    if (![self isMe]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    parameters[@"source"] = @"3";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            [self.dataArray removeObject:item];
            [self.collectionView deleteItemsAtIndexPaths:@[touchIndexPath]];
            
            [SVProgressHUD showSuccessWithStatus:@"剪切成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
        
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self.collectionView addGestureRecognizer:self.longPressGesture];
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"剪切";
        attributes[@"ID"] = item.ID;
        attributes[@"content"] = item.content;
        attributes[@"fmt"] = item.fmt;
        [SJStatisticTool event:@"cutItem" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
    }];
}


#pragma mark - SJUploadBarDelegate

- (void)uploadWord {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddWordViewController *addVC = [SJAddWordViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.item = self.item;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)uploadPicture {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"] && [dict[@"h"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddPicViewController *addVC = [SJAddPicViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.item = self.item;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)fromSS {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddFromSSViewController *addVC = [SJAddFromSSViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.item = self.item;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)uploadTxt {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"] && [dict[@"h"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddTxtViewController *addVC = [SJAddTxtViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.item = self.item;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
    
}

- (void)uploadBar:(SJUploadBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 词条
            [weakSelf uploadWord];
        }
        
        if (index == 1) { // 文本
            [weakSelf uploadTxt];
        }
        
        if (index == 2) { // 图片
            [weakSelf uploadPicture];
        }
        
        if (index == 3) { // 从空间站选择
            [weakSelf fromSS];
        }
        
    }];
}

- (void)alertUploadBar {
    
    SJUploadBar *uploadBar = [[SJUploadBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(60))];
    uploadBar.delegate = self;
    
    WeakSelf;
    [LEEAlert actionsheet].config
    .LeeAddCustomView(^(LEECustomView *custom) {
        custom.view = uploadBar;
        custom.isAutoWidth = YES;
    })
    .LeeMaxWidth(SJScreenW)
    .LeeHeaderColor([UIColor clearColor])
    .LeeBackgroundStyleTranslucent(0)
    .LeeActionSheetBottomMargin(SJLayoutFrame(11))
    .LeeHeaderInsets(UIEdgeInsetsZero)
    .LeeCloseComplete(^{
        [weakSelf.touchView removeFromSuperview];
        weakSelf.touchView = nil;
    })
    .LeeShow();
}

- (void)addItem {
    
    // 检索
    int max_t = 0;
    for (SJWordItem *item in self.dataArray) {

        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }

    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    for (int i = 0; i < max_t + max_w; i++) {

        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];

        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }

    for (SJWordItem *item in self.dataArray) {

        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];

        for (int i = t; i < t + h; i++) {

            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }

    int l2r = 0;
    NSMutableArray *optArray = [NSMutableArray array];

    if ([self.t intValue] >= arrlt.count - max_w) {

        int maxOptW = max_w - [self.l intValue];
        int maxOptH = max_w;

        for (int i = 0; i < maxOptH; i++) {

            for (int j = 0; j < maxOptW; j++) {

                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = [NSString stringWithFormat:@"%d", i + 1];
                dict[@"w"] = [NSString stringWithFormat:@"%d", j + 1];
                [optArray addObject:dict];
            }
        }

    } else {

        for (int i = [self.l intValue]; i < max_w; i++) { // 第1行
            
            if ([arrlt[[self.t intValue]][i] isEqualToNumber: @0]) {
                
                l2r = i - [self.l intValue] + 1;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = @"1";
                dict[@"w"] = [NSString stringWithFormat:@"%d", l2r];
                [optArray addObject:dict];
                
            } else {
                break;
            }
        }
        
        for (int n = 1; n < max_w; n++) { // 2 ~ max_w 行
            
            for (int i = [self.l intValue]; i < max_w; i++) {
                
                if ([arrlt[[self.t intValue] + n][i] isEqualToNumber: @0]) {
                    
                    if (i - [self.l intValue] + 1 <= l2r) {
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        dict[@"h"] = [NSString stringWithFormat:@"%d", n + 1];
                        dict[@"w"] = [NSString stringWithFormat:@"%d", i - [self.l intValue] + 1];
                        [optArray addObject:dict];
                    } else {
                        break;
                    }
                    
                } else {
                    l2r = i - [self.l intValue];
                    break;
                }
            }
        }
    }
    
    if (optArray.count == 0) {
        return;
    }
    
    self.optionArray = optArray;

    [self alertUploadBar];
    
    // 显示点击区域
    [self.collectionView addSubview:self.touchView];
    
    int lNum = [self.l intValue];
    int tNum = [self.t intValue];
    
    CGFloat headerH = [self collectionView:nil layout:nil heightForHeaderInSection:0];
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin + headerH; // 设置上面的 margin
    
    self.touchView.sd_layout
    .leftSpaceToView(self.collectionView, x)
    .topSpaceToView(self.collectionView, y)
    .heightIs(SJItemWH)
    .widthIs(SJItemWH);
}


#pragma mark - 移动相关

- (void)cellSelectedAtIndexPath:(NSIndexPath *)indexPath{
    
    SJOneCell *cell = (SJOneCell *)[self.collectionView cellForItemAtIndexPath:indexPath] ;
    
    self.selectedIndexPath = indexPath;
    self.selectedCell = cell;
    self.snapshot = [self customSnapshotFromView:cell];
    
    [self.collectionView addSubview:self.snapshot];
    
    cell.hidden = YES;
    CGPoint center = self.snapshot.center;
    center.y = self.touchPoint.y;
    center.x = self.touchPoint.x;
    WeakSelf;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.snapshot.center = center;
    }];
}

#pragma 返回一个给定view的截图.
- (UIView *)customSnapshotFromView:(UIView *)inputView {
    
    // Make an image from the input view.
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Create an image view.
    UIView *snapshot = [[UIImageView alloc] initWithImage:image];
    snapshot.center = inputView.center;
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}

/**
 拖动中调用
 */
- (void)gestureChangedAtPoint:(CGPoint)point {
    
    // 截图跟随手指移动
    CGPoint center = self.snapshot.center;
    center.y = point.y;
    center.x = point.x;
    self.snapshot.center = center;
    
    if ([self checkIfSnapshotMeetsEdge]) {
        [self startAutoScrollTimer];
    }else{
        [self stopAutoScrollTimer];
    }
}

#pragma 检查截图是否到达整个collectionView的边缘，并作出响应
- (BOOL)checkIfSnapshotMeetsEdge {
    
    CGFloat minY = CGRectGetMinY(_snapshot.frame);
    CGFloat maxY = CGRectGetMaxY(_snapshot.frame);
    if (minY < self.collectionView.contentOffset.y) {
        _autoScrollDirection = @"1";
        return YES;
    }
    if (maxY > self.collectionView.bounds.size.height + self.collectionView.contentOffset.y) {
        _autoScrollDirection = @"2";
        return YES;
    }
    return NO;
}

#pragma timer methods
/**
 *  创建定时器并运行
 */
- (void)startAutoScrollTimer{
    if (!_autoScrollTimer) {
        _autoScrollTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(startAutoScroll)];
        [_autoScrollTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
}
/**
 *  停止定时器并销毁
 */
- (void)stopAutoScrollTimer{
    if (_autoScrollTimer) {
        [_autoScrollTimer invalidate];
        _autoScrollTimer = nil;
    }
}

#pragma mark - 开始自动滚动
- (void)startAutoScroll {
    
    CGFloat pixelSpeed = 4;
    if ([_autoScrollDirection isEqualToString:@"1"]) { //向下滚动
        if (self.collectionView.contentOffset.y > 0) { //向下滚动最大范围限制
            [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.contentOffset.y - pixelSpeed)];
            _snapshot.center = CGPointMake(_snapshot.center.x, _snapshot.center.y - pixelSpeed);
        }
    } else { //向上滚动
        if (self.collectionView.contentOffset.y + self.collectionView.bounds.size.height < self.collectionView.contentSize.height) { //向下滚动最大范围限制
            [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.contentOffset.y + pixelSpeed)];
            _snapshot.center = CGPointMake(_snapshot.center.x, _snapshot.center.y + pixelSpeed);
        }
    }
}

/**
 拖动完成调用
 */
- (void)gestureEnded {
    
    [self stopAutoScrollTimer];
    [self didEndDraging];
}


/**
 *  拖拽结束，显示cell，并移除截图
 */
- (void)didEndDraging {
    
    SJWordItem *selectedItem = self.dataArray[self.selectedIndexPath.row];
    // 检索
    int max_t = 0;
    
    for (SJWordItem *item in self.dataArray) {
        
        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }
    
    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    
    for (int i = 0; i < max_t + max_w * 2; i++) {
        
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];
        
        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }
    
    for (SJWordItem *item in self.dataArray) {
        
        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        if (selectedItem == item) {
            continue;
        }
        
        for (int i = t; i < t + h; i++) {
            
            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }
    
    CGFloat headerH = [self collectionView:nil layout:nil heightForHeaderInSection:0];
    
    int l = (int)(self.snapshot.frame.origin.x / ((SJScreenW - SJMargin) / SJItemCount));
    int t = (int)((self.snapshot.frame.origin.y + SJMargin - headerH) / ((SJScreenW - SJMargin) / SJItemCount)); // 空置 上沿
    int w = [selectedItem.w intValue];
    int h = [selectedItem.h intValue];
    
    BOOL isMove = YES;
    
    for (int i = t; i < t + h; i++) {
        
        if (l + w > max_w || l < 0 || t < 0) {
            isMove = NO;
            break;
        }
        
        for (int j = l; j < l + w; j++) {
            
            if ([arrlt[i][j] isEqualToValue:@1]) {
                
                isMove = NO;
                break;
            }
        }
    }
    
    if (isMove) { // 可以移动
        [self moveNodeWithItem:selectedItem l:l t:t];
        
    } else {  // 不可移动
        
        [SVProgressHUD showInfoWithStatus:@"位置不足"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        [self removeNode];
    }
}

- (void)moveNodeWithItem:(SJWordItem *)item l:(int)l t:(int)t {
    
    if (![self isMe]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    parameters[@"l"] = [NSString stringWithFormat:@"%i", l];
    parameters[@"t"] = [NSString stringWithFormat:@"%i", t];
    parameters[@"h"] = item.h;
    parameters[@"w"] = item.w;
    parameters[@"pid"] = self.item.bid;
    
    SJMovePosApi *api = [[SJMovePosApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            item.t = [NSString stringWithFormat:@"%i", t];
            item.l = [NSString stringWithFormat:@"%i", l];
            int lNum = [item.l intValue];
            int tNum = [item.t intValue];
            
            CGFloat headerH = [self collectionView:nil layout:nil heightForHeaderInSection:0];
            CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
            CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin + headerH;
            
            [UIView animateWithDuration:0.2 animations:^{
                _snapshot.left_sd = x;
                _snapshot.top_sd = y;
                
            } completion:^(BOOL finished) {
                [_snapshot removeFromSuperview];
                _snapshot = nil;
                [self.collectionView addGestureRecognizer:self.longPressGesture];
                [self.collectionView reloadData];
            }];
            
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            attributes[@"name"] = @"移动";
            attributes[@"ID"] = item.ID;
            attributes[@"content"] = item.content;
            attributes[@"fmt"] = item.fmt;
            [SJStatisticTool event:@"moveItem" attributes:attributes];
            
        } else {
            [self removeNode];
        }
        
    } failure:^(YTKBaseRequest *request) {
        [self removeNode];
    }];
}

- (void)removeNode {
    
    WeakSelf;
    [self stopAutoScrollTimer];
    [UIView animateWithDuration:0.2 animations:^{
        _snapshot.center = self.selectedCell.center;
    } completion:^(BOOL finished) {
        
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        [self.collectionView addGestureRecognizer:self.longPressGesture];
        weakSelf.selectedCell.hidden = NO;
    }];
}

#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJScreenW;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout heightForHeaderInSection:(NSInteger)section {
    
    int hNum = [self.item.h intValue];
    
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return h + 2 * SJMargin;
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:SJ_UICollectionElementKindSectionHeader]) {
        
        SJTreeHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SJTreeHeaderView class]) forIndexPath:indexPath];
        
        int wNum = [self.item.w intValue];
        int hNum = [self.item.h intValue];
        CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
        CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
        header.contentSize = CGSizeMake(w, h);
        
        header.isDisplayTitle = self.isDisplayTitle;
        header.item = self.item;
        
        return header;
        
    } else if ([kind isEqualToString:SJ_UICollectionElementKindSectionFooter]){
        
        return nil;
    }
    
    return nil;
}


//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//
//    if ([self isMe]) {
//        return 1;
//    } else {
//        return 2;
//    }
//}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    cell.isDisplayTitle = self.isDisplayTitle;
    cell.item = item;
    
    if (cell.hidden) {
        cell.hidden = NO;
    }
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"1"]) { // 文字
        
        [self tapText:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        [self tapPic:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        [self tapAudio:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"音频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Audio" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        [self tapVideo:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"视频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Video" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
        
        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
        txtVC.item = item;
        txtVC.hasMore = YES;
        txtVC.dataArray = self.dataArray;
        txtVC.popToVc = self;
        [self.navigationController pushViewController:txtVC animated:YES];
    }
    
    
//    if ([item.fmt isEqualToString:@"1"]) {
//
//        self.selectedItem = item;
//        [self tapText:(SJOneCell *)cell item:item];
//    } else {
//        [self becomeZero:item];
//    }
}

- (void)becomeZero:(SJWordItem *)item {
    
    NSInteger index = [self.items indexOfObject:self.item];
    
    self.item.offsetY = [NSString stringWithFormat:@"%f", self.collectionView.contentOffset.y];
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (int i = 0; i < self.items.count; i++) {
        if (i <= index) {
            [tempArray addObject:self.items[i]];
        }
    }
    
    self.items = tempArray;
    self.item = item;
    
    
    [self.items addObject:self.item];
    self.preButton.hidden = NO;
    self.nextButton.hidden = YES;
    
    [self loadNewData];
    
    NSString *imageName = @"guide_01_front&back";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName]) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    [self becomeZero:item];
    
//    self.selectedItem = item;
//
//    if ([item.fmt isEqualToString:@"1"]) { // 文字
//
//        [self becomeZero:item];
//
//    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
//
//        [self tapPic:(SJOneCell *)cell item:item];
//
//    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
//
//        [self tapAudio:(SJOneCell *)cell item:item];
//
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"音频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Audio" attributes:attributes];
//
//    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
//
//        [self tapVideo:(SJOneCell *)cell item:item];
//
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"视频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Video" attributes:attributes];
//
//    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
//
//        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
//        txtVC.item = item;
//        txtVC.hasMore = YES;
//        txtVC.dataArray = self.dataArray;
//        txtVC.popToVc = self;
//        [self.navigationController pushViewController:txtVC animated:YES];
//    }
}

- (void)tapAudio:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    SJExtraItem *extra = [SJExtraItem modelWithJSON:item.extra];
    
    if (extra.cover) {
        NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, extra.cover];
        imageInfo.imageURL = [NSURL URLWithString:urlString];
    } else {
        UIImage *img = [UIImage imageNamed:@"icn_audio"];
        imageInfo.image = img;
        imageInfo.referenceContentMode = UIViewContentModeCenter;
    }
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.player play];
    
}


- (void)tapVideo:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceContentMode = UIViewContentModeCenter;
    UIImage *img = [UIImage imageNamed:@"common_trans_square"];
    
    imageInfo.image = img;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
    // 视频
    [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
        // do something  必须清了缓存？才能播放？
    }];
    
    self.videoContainer = ({
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor blackColor];
        videoView.frame = CGRectMake(0, 0, SJScreenW, SJScreenW * 9.0 / 16.0);
        [imageViewer.imageView addSubview:videoView];
        
        videoView;
    });
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.videoContainer addGestureRecognizer:tapGestureRecognizer];
    self.videoContainer.jp_videoPlayerDelegate = self;
    [self.videoContainer jp_perfersPlayingProgressViewColor:SJColorHexString(@"#f76a4a")];
    [self.videoContainer jp_perfersDownloadProgressViewColor:[UIColor lightGrayColor]];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    [self.videoContainer jp_playVideoWithURL:[NSURL URLWithString:urlString]];
    
}

- (void)tapText:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = item.content;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    titleLabel.size_sd = CGSizeMake(SJScreenW - SJLayoutFrame(40), SJScreenH);
    
    UIImage *img = [titleLabel.layer snapshotImage];
    while (!img) { // 这样好吗？
        img = [titleLabel.layer snapshotImage];
    }
    
    imageInfo.image = img;
    
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
}

- (void)tapPic:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, item.content];
    imageInfo.imageURL = [NSURL URLWithString:urlString];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceCornerRadius = 6;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldDownloadVideoForURL:(NSURL *)videoURL{
    return YES;
}

- (BOOL)shouldProgressViewOnTop{
    return NO;
}

- (BOOL)shouldAutoReplayAfterPlayCompleteForURL:(nonnull NSURL *)videoURL {
    
    return YES;
}

- (void)playingStatusDidChanged:(JPVideoPlayerPlayingStatus)playingStatus{
    
    SJLog(@"playingStatus-----%ld", (long)playingStatus);
    
}

//- (void)downloadingProgressDidChanged:(CGFloat)downloadingProgress{
//    SJLog(@"downloadingProgress------%0.2lf", downloadingProgress);
//}
//
//- (void)playingProgressDidChanged:(CGFloat)playingProgress{
//    SJLog(@"playingProgress------%0.2lf", playingProgress);
//}

#pragma mark - Tap Event

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusPortrait) {
            [self.videoContainer jp_gotoLandscapeAnimated:YES completion:^{
            }];
        }
        else if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusLandscape) {
            [self.videoContainer jp_gotoPortraitAnimated:YES completion:^{
            }];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma JTSImageViewControllerAnimationDelegate

- (void)imageViewerWillBeginPresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView {
    
}

- (void)imageViewerWillAnimatePresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration { // 显示完 图片墙 did
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf showDetaillInView:containerView];
    });
    
    
}

- (void)imageViewer:(JTSImageViewController *)imageViewer willAdjustInterfaceForZoomScale:(CGFloat)zoomScale withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
}

- (void)imageViewerWillBeginDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView { // 将要消失 图片墙 will
    
    // 删除详情
    [self hideDetaill];
    
    if ([self.selectedItem.fmt isEqualToString:@"4"]) {
        
        [self.videoContainer jp_stopPlay];
        [self.videoContainer removeFromSuperview];
        self.videoContainer = nil;
    }
    
    if ([self.selectedItem.fmt isEqualToString:@"3"]) {
        
        [self.player pause];
        self.player = nil;
    }
    
    self.imageViewer = nil;
}

- (void)imageViewerWillAnimateDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
    
}


- (void)showDetaillInView:(UIView *)view {
    
    [view addSubview:self.detailImageView];
    self.detailImageView.sd_layout
    .heightIs(SJLayoutFrame(45))
    .leftSpaceToView(view, SJLayoutFrame(0))
    .rightSpaceToView(view, SJLayoutFrame(0))
    .bottomSpaceToView(view, SJLayoutFrame(0));
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
    self.detailLabel.text = extraItem.t;
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailImageView.alpha = 1;
    }];
    
}

- (void)hideDetaill {
    
    [self.detailImageView removeAllSubviews];
    [self.detailImageView removeFromSuperview];
    self.detailImageView = nil;
    self.detailLabel = nil;
    
}

#pragma mark - request

- (void)loadNewData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    parameters[@"id"] = self.item.ID;
    
    if (self.pageType && self.items.count == 1) {
        parameters[@"page"] = self.pageType;
    }
    
    SJTreeApi *api = [[SJTreeApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"data"][@"cur"] intValue];
        
        } else {
            [self.dataArray removeAllObjects];
        }
        
        self.userItem = [SJUserInfoItem modelWithJSON:api.responseObject[@"content"][@"block"][@"user_info"]];
        self.blockItem = [SJBlockItem modelWithJSON:api.responseObject[@"content"][@"block"]];
        
        [self.avatarImageView setImageWithURL:[NSURL URLWithString:self.userItem.avatar] placeholder:[UIImage imageNamed:@"common_icon_defaultavatar"]];
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"data"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
        
        self.item.subWords = [self.dataArray mutableCopy];
        
        self.userItem = [SJUserInfoItem modelWithJSON:api.responseObject[@"content"][@"block"][@"user_info"]];
        self.blockItem = [SJBlockItem modelWithJSON:api.responseObject[@"content"][@"block"]];
        
        self.item.userItem = [api.responseObject[@"content"][@"block"][@"user_info"] mutableCopy];
        self.item.blockItem = [api.responseObject[@"content"][@"block"] mutableCopy];
        
        [self.avatarImageView setImageWithURL:[NSURL URLWithString:self.userItem.avatar] placeholder:[UIImage imageNamed:@"common_icon_defaultavatar"]];
        
        self.item.is_published = self.blockItem.is_published;
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
        self.collectionView.contentOffset = CGPointMake(0, SJLayoutFrame(-50));
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    parameters[@"id"] = self.item.ID;
    
    if (self.pageType && self.items.count == 1) {
        parameters[@"page"] = self.pageType;
    }

    SJTreeApi *api = [[SJTreeApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"data"][@"cur"] intValue];
            
        } else {
            self.page--;
        }
        
        self.item.subWords = [self.dataArray mutableCopy];
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}

@end

